<template>
  <el-drawer
    :append-to-body="true"
    :before-close="saveApprover"
    :wrapper-closable="false"
    v-model="approverDrawer"
    class="set_promoter"
    direction="rtl"
    size="550px"
    :title="$t('workflow.flowDesign.approverSettings')"
  >
    <div class="demo-drawer__content">
      <div class="drawer_content">
        <div class="approver_content">
          <el-tabs
            v-model="activeName"
            type="card"
          >
            <el-tab-pane
              :label="$t('workflow.flowDesign.baseSetting')"
              name="base"
            >
              <el-input
                v-model="approverConf.nodeName"
                size="default"
                class="mb20"
                :placeholder="$t('workflow.flowDesign.nodeNamePlaceholder')"
              />
              <div class="medium-font-size text-primary-color mb10">{{ $t("workflow.flowDesign.approverSettings") }}</div>
              <el-radio-group
                v-model="approverConf.settype"
                style="display: block"
              >
                <el-radio
                  :value="t.value"
                  :key="t.value"
                  :label="t.value"
                  v-for="t in setTypeList"
                >
                  {{ t.label }}
                </el-radio>
              </el-radio-group>
              <div v-if="approverConf.settype === 1">
                <div>
                  <el-button
                    icon="ele-Plus"
                    size="default"
                    @click="addApprover"
                  >
                    {{ $t("workflow.flowDesign.addModifyMembers") }}
                  </el-button>
                  <p class="selected_list">
                    <span
                      v-for="(item, index) in approverConf.nodeUserList"
                      :key="index"
                      class="el-tag"
                    >
                      {{ item.nickName }}
                      <el-icon @click="approverConf.nodeUserList.splice(index, 1)"><ele-Close /></el-icon>
                    </span>
                    <a
                      v-if="approverConf.nodeUserList && approverConf.nodeUserList.length != 0"
                      @click="approverConf.nodeUserList = []"
                    >
                      {{ $t("workflow.flowDesign.clear") }}
                    </a>
                  </p>
                </div>
                <div>
                  <el-button
                    icon="ele-Plus"
                    size="default"
                    @click="addRoleApprover"
                  >
                    {{ $t("workflow.flowDesign.addModifyRoles") }}
                  </el-button>
                  <p class="selected_list">
                    <span
                      v-for="(item, index) in approverConf.nodeRoleList"
                      :key="index"
                      class="el-tag"
                    >
                      {{ item.roleName }}
                      <el-icon @click="approverConf.nodeRoleList.splice(index, 1)"><ele-Close /></el-icon>
                    </span>
                    <a
                      v-if="approverConf.nodeRoleList && approverConf.nodeRoleList.length != 0"
                      @click="approverConf.nodeRoleList = []"
                    >
                      {{ $t("workflow.flowDesign.clear") }}
                    </a>
                  </p>
                </div>
                <div>
                  <el-button
                    icon="ele-Plus"
                    size="default"
                    @click="addPostApprover"
                  >
                    {{ $t("workflow.flowDesign.addModifyPositions") }}
                  </el-button>
                  <p class="selected_list">
                    <span
                      v-for="(item, index) in approverConf.nodePostList"
                      :key="index"
                      class="el-tag"
                    >
                      {{ item.postName }}
                      <el-icon @click="approverConf.nodePostList.splice(index, 1)"><ele-Close /></el-icon>
                    </span>
                    <a
                      v-if="approverConf.nodePostList && approverConf.nodePostList.length != 0"
                      @click="approverConf.nodePostList = []"
                    >
                      {{ $t("workflow.flowDesign.clear") }}
                    </a>
                  </p>
                </div>
              </div>
              <div
                v-if="approverConf.settype === 2"
                class="flex-align-center mb20"
              >
                <span>{{ $t("workflow.flowDesign.sponsoring") }} ：</span>
                <el-select
                  class="select-width"
                  size="default"
                  v-model="approverConf.approveDirectorLevel"
                  :placeholder="$t('workflow.flowDesign.choose')"
                >
                  <el-option
                    v-for="lm in levelManagerList"
                    :key="lm.value"
                    :label="lm.label"
                    :value="lm.value"
                  />
                </el-select>
              </div>
              <div
                v-if="approverConf.settype === 3"
                class="text-secondary-color"
              >
                {{ $t("workflow.flowDesign.initiatorHimselfApprover") }}
              </div>
              <div
                v-if="approverConf.settype === 4"
                class="text-secondary-color"
              >
                <div class="base-font-size text-primary-color mb20">
                  {{ $t("workflow.flowDesign.selectMemberFieldInForm") }} ：
                  <el-select
                    class="select-width"
                    size="default"
                    v-model="approverConf.formUserFields"
                    :placeholder="$t('workflow.flowDesign.chooseLabel')"
                  >
                    <el-option
                      v-for="item in getUserFieldList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </div>
              <div
                v-if="approverConf.settype === 5"
                class="text-secondary-color"
              >
                <div class="base-font-size text-primary-color mb20">
                  {{ $t("workflow.flowDesign.selectDeptFieldInForm") }} ：
                  <el-select
                    class="select-width"
                    size="default"
                    v-model="approverConf.formDeptFields"
                    :placeholder="$t('workflow.flowDesign.chooseLabel')"
                  >
                    <el-option
                      v-for="item in getDeptFieldList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
                <div class="base-font-size text-primary-color mb20">
                  <span>{{ $t("workflow.flowDesign.selectField") }} ：</span>
                  <el-select
                    class="select-width"
                    size="default"
                    v-model="approverConf.formDeptFieldLevel"
                    :placeholder="$t('workflow.flowDesign.choose')"
                  >
                    <el-option
                      v-for="lm in levelManagerList"
                      :key="lm.value"
                      :label="lm.label"
                      :value="lm.value"
                    />
                  </el-select>
                  <div class="text-desc">{{ $t("workflow.flowDesign.selectDeptFieldInFormDesc") }}</div>
                </div>
              </div>
              <div v-if="approverConf.settype !== 3">
                <div class="text-primary-color medium-font-size mb20">
                  {{ $t("workflow.flowDesign.multipleApprovalMethod") }}
                </div>
                <el-radio-group
                  class="block-radio-group"
                  v-model="approverConf.multipleApprovalType"
                >
                  <el-radio
                    value="1"
                    v-if="approverConf.settype !== 2"
                  >
                    {{ $t("workflow.flowDesign.countersignature") }}
                  </el-radio>
                  <el-radio value="2">{{ $t("workflow.flowDesign.discretionary") }}</el-radio>
                </el-radio-group>
              </div>
            </el-tab-pane>
            <el-tab-pane
              :label="$t('workflow.flowDesign.formPermissions')"
              name="field"
            >
              <el-table
                :data="approverConf.formProperties"
                style="width: 100%"
              >
                <el-table-column
                  :label="$t('workflow.flowDesign.fieldName')"
                  prop="name"
                />
                <el-table-column
                  :label="$t('workflow.flowDesign.opration')"
                  prop="id"
                >
                  <template #header>
                    <div class="flex-align-center">
                      <span>{{ $t("workflow.flowDesign.opration") }}</span>
                      <div class="ml10">
                        <el-checkbox
                          v-model="allReadable"
                          @change="handleAllReadableChange"
                        >
                          {{ $t("workflow.flowDesign.visible") }}
                        </el-checkbox>
                        <el-checkbox
                          v-model="allWriteable"
                          @change="handleAllWriteableChange"
                        >
                          {{ $t("workflow.flowDesign.editable") }}
                        </el-checkbox>
                      </div>
                    </div>
                  </template>
                  <template #default="scope">
                    <el-checkbox v-model="scope.row['readable']">{{ $t("workflow.flowDesign.visible") }}</el-checkbox>
                    <el-checkbox
                      v-if="!scope.row.displayType"
                      v-model="scope.row['writeable']"
                    >
                      {{ $t("workflow.flowDesign.editable") }}
                    </el-checkbox>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane
              :label="$t('workflow.flowDesign.nodeProp')"
              name="prop"
            >
              <el-form>
                <el-form-item :label="$t('workflow.flowDesign.approvalNodeAdviceStatus')">
                  <el-radio-group v-model="approverConf.adviceStatus">
                    <el-radio :value="1">{{ $t("workflow.flowDesign.enable") }}</el-radio>
                    <el-radio :value="0">{{ $t("workflow.flowDesign.disable") }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item :label="$t('workflow.flowDesign.approvalSignPadStatus')">
                  <el-radio-group v-model="approverConf.signPadStatus">
                    <el-radio :value="1">{{ $t("workflow.flowDesign.enable") }}</el-radio>
                    <el-radio :value="0">{{ $t("workflow.flowDesign.disable") }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item :label="$t('workflow.flowDesign.nodePropBtns')">
                  <el-checkbox-group
                    v-model="approverConf.operationBtnList"
                    :min="1"
                  >
                    <el-checkbox value="agree">{{ $t("formI18n.all.agree") }}</el-checkbox>
                    <el-checkbox value="return">{{ $t("formI18n.all.return") }}</el-checkbox>
                    <el-checkbox value="reject">{{ $t("formI18n.all.refuse") }}</el-checkbox>
                    <el-checkbox value="transfer">{{ $t("formI18n.all.transfer") }}</el-checkbox>
                    <el-checkbox value="delegate">{{ $t("formI18n.all.delegate") }}</el-checkbox>
                    <el-checkbox value="addSignBefore">{{ $t("formI18n.all.addSignBefore") }}</el-checkbox>
                    <el-checkbox value="addSignAfter">{{ $t("formI18n.all.addSignAfter") }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane
              :label="$t('workflow.flowDesign.taskEvents')"
              name="event"
            >
              <el-alert
                :title="$t('workflow.flowDesign.postPushTargetInterface')"
                :closable="false"
                type="warning"
              />
              <el-form
                label-position="top"
                label-width="80px"
                :model="approverConf.taskEvents"
              >
                <el-form-item :label="$t('workflow.flowDesign.customizeApprovalEvent')">
                  <el-switch v-model="approverConf.taskEvents.agree" />
                </el-form-item>
                <el-form-item
                  v-if="approverConf.taskEvents.agree"
                  :label="$t('workflow.flowDesign.approvalRequestURL')"
                >
                  <template #label>
                    <span>
                      {{ $t("workflow.flowDesign.approvalRequestURL") }}
                      <el-tooltip
                        :content="$t('workflow.flowDesign.contentText')"
                        placement="top"
                      >
                        <el-icon><ele-QuestionFilled /></el-icon>
                      </el-tooltip>
                    </span>
                  </template>
                  <el-input
                    v-model="approverConf.taskEvents.agreeNotifyUrl"
                    :placeholder="$t('workflow.flowDesign.contentText2')"
                  >
                    <template #prepend>POST</template>
                  </el-input>
                </el-form-item>
                <el-form-item :label="$t('workflow.flowDesign.customizeRejectEvent')">
                  <el-switch v-model="approverConf.taskEvents.reject" />
                </el-form-item>
                <el-form-item
                  v-if="approverConf.taskEvents.reject"
                  :placeholder="$t('workflow.flowDesign.rejectRequestURL')"
                >
                  <template #label>
                    <span>
                      {{ $t("workflow.flowDesign.rejectRequestURL") }}
                      <el-tooltip
                        :content="$t('workflow.flowDesign.contentText')"
                        placement="top"
                      >
                        <el-icon><ele-QuestionFilled /></el-icon>
                      </el-tooltip>
                    </span>
                  </template>
                  <el-input
                    v-model="approverConf.taskEvents.rejectNotifyUrl"
                    :placeholder="$t('workflow.flowDesign.contentText2')"
                  >
                    <template #prepend>POST</template>
                  </el-input>
                </el-form-item>
                <el-form-item :label="$t('workflow.flowDesign.enableCpWxNotify')">
                  <template #label>
                    <span>
                      {{ $t("workflow.flowDesign.enableCpWxNotify") }}
                      <el-tooltip
                        :content="$t('workflow.flowDesign.enableCpWxNotifyTips')"
                        placement="top"
                      >
                        <el-icon><ele-QuestionFilled /></el-icon>
                      </el-tooltip>
                    </span>
                  </template>
                  <el-switch v-model="approverConf.taskEvents.enableCpWxNotify" />
                </el-form-item>
                <el-form-item :label="$t('workflow.flowDesign.enableWxMpNotify')">
                  <template #label>
                    <span>
                      {{ $t("workflow.flowDesign.enableWxMpNotify") }}
                      <el-tooltip
                        :content="$t('workflow.flowDesign.enableWxMpNotifyTips')"
                        placement="top"
                      >
                        <el-icon><ele-QuestionFilled /></el-icon>
                      </el-tooltip>
                    </span>
                  </template>
                  <el-switch v-model="approverConf.taskEvents.enableWxMpNotify" />
                  <el-link
                    :underline="false"
                    class="ml10"
                    size="default"
                    type="primary"
                    @click="showMsgConfigTemplate = true"
                  >
                    {{ $t("workflow.flowDesign.configTemplate") }}
                  </el-link>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
        <user-choose-table
          ref="userChooseTableRef"
          @submit="sureApprover"
        />
        <role-choose-table
          ref="roleChooseTableRef"
          @submit="sureRoleApprover"
        />
        <post-choose-table
          ref="postChooseTableRef"
          @submit="surePostApprover"
        />
      </div>
    </div>
    <template #footer>
      <div class="pb20 pr20">
        <el-button
          @click="closeDrawer"
          size="default"
        >
          {{ $t("formI18n.all.cancel") }}
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="saveApprover"
        >
          {{ $t("formI18n.all.confirm") }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { i18n } from "@/i18n";
import { cloneDeep } from "lodash-es";
import { useFormWorkflow } from "@/stores/formWorkflow";
import { storeToRefs } from "pinia";
import { MessageUtil } from "@/utils/messageUtil";
import { isEmpty } from "@/utils";
import UserChooseTable from "@/views/system/user/chooseTable.vue";
import RoleChooseTable from "@/views/system/role/chooseTable.vue";
import PostChooseTable from "@/views/system/post/chooseTable.vue";

// Store and reactive states
const formWorkflowStore = useFormWorkflow();

const { approverConfig, approverDrawer, formFields, showMsgConfigTemplate } = storeToRefs(formWorkflowStore);

const activeName = ref("base");

const approverConf = ref({
  settype: 1,
  multipleApprovalType: "2",
  nodeUserList: [],
  nodeRoleList: [],
  nodePostList: [],
  taskEvents: {
    agree: false,
    agreeNotifyUrl: "",
    reject: false,
    rejectNotifyUrl: "",
    enableCpWxNotify: false,
    enableWxMpNotify: false
  },
  approveDirectorLevel: null,
  formUserFields: null,
  formDeptFields: null,
  formDeptFieldLevel: null,
  signPadStatus: 0,
  adviceStatus: 1,
  operationBtnList: ["agree", "return", "reject", "transfer", "delegate", "addSignBefore", "addSignAfter"]
});
const approverVisible = ref(false);
const approverRoleVisible = ref(false);
const approverPostVisible = ref(false);
const checkedRoleList = ref<any[]>([]);
const checkedPostList = ref<any[]>([]);
const checkedList = ref<any[]>([]);

const setTypeList = ref([
  {
    value: 1,
    label: i18n.global.t("workflow.flowDesign.specifyApprovers")
  },
  {
    value: 2,
    label: i18n.global.t("workflow.flowDesign.departmentManager")
  },
  {
    value: 3,
    label: i18n.global.t("workflow.flowDesign.initiatorHimself")
  },
  {
    value: 4,
    label: i18n.global.t("workflow.flowDesign.memberFieldInForm")
  },
  {
    value: 5,
    label: i18n.global.t("workflow.flowDesign.deptFieldInForm")
  }
]);

const levelManagerList = ref([
  {
    value: "1",
    label: i18n.global.t("workflow.flowDesign.level1Manager")
  },
  {
    value: "2",
    label: i18n.global.t("workflow.flowDesign.level2Manager")
  },
  {
    value: "3",
    label: i18n.global.t("workflow.flowDesign.level3Manager")
  },
  {
    value: "4",
    label: i18n.global.t("workflow.flowDesign.level4Manager")
  },
  {
    value: "5",
    label: i18n.global.t("workflow.flowDesign.level5Manager")
  },
  {
    value: "6",
    label: i18n.global.t("workflow.flowDesign.level6Manager")
  }
]);

// 非重复 第一个.value是vue的语法
watch(
  () => approverConfig.value?.value,
  val => {
    initApproverConfig(val);
  }
);

// Methods
const initApproverConfig = (val: any) => {
  console.log(val);
  if (val && !val.formProperties) {
    val.formProperties = cloneDeep(formProperties.value);
  } else if (val) {
    // 处理后面新增字段
    const tempFormProperties = cloneDeep(val?.formProperties || []);
    val.formProperties = [];
    formProperties.value.forEach(prop => {
      const item = tempFormProperties.find((item: any) => item.id === prop.id);
      if (item) {
        val.formProperties.push(
          cloneDeep({
            ...item,
            name: prop.name
          })
        );
      } else {
        val.formProperties.push({
          ...cloneDeep(prop),
          readable: false,
          writeable: false
        });
      }
    });
    allReadable.value = val.formProperties.every(item => item.readable);
    allWriteable.value = val.formProperties.every(item => item.writeable);
  }
  const copyApproverConf = cloneDeep(approverConf.value);
  // 避免加了一些字段
  Object.assign(copyApproverConf, val);
  approverConf.value = copyApproverConf;
};

const userChooseTableRef = ref<InstanceType<typeof UserChooseTable> | null>(null);
const roleChooseTableRef = ref<InstanceType<typeof RoleChooseTable> | null>(null);
const postChooseTableRef = ref<InstanceType<typeof RoleChooseTable> | null>(null);

const addApprover = () => {
  approverVisible.value = true;
  checkedList.value = approverConf.value.nodeUserList;
  userChooseTableRef.value.showDialog(checkedList.value);
};

const addRoleApprover = () => {
  approverRoleVisible.value = true;
  checkedRoleList.value = approverConf.value.nodeRoleList;
  roleChooseTableRef.value.showDialog(checkedRoleList.value);
};

const addPostApprover = () => {
  approverPostVisible.value = true;
  checkedPostList.value = approverConf.value.nodePostList;
  postChooseTableRef.value.showDialog(checkedPostList.value);
};

const sureApprover = (data: any) => {
  console.log(data);
  approverConf.value.nodeUserList = data.map(item => {
    return {
      id: item.id,
      userName: item.userName,
      nickName: item.nickName
    };
  });
  approverVisible.value = false;
};

const sureRoleApprover = (data: any) => {
  console.log(data);
  approverConf.value.nodeRoleList = data.map(item => ({
    id: item.id,
    roleKey: item.roleKey,
    roleName: item.roleName
  }));
  approverRoleVisible.value = false;
};

const surePostApprover = (data: any) => {
  console.log(approverConf.value.nodePostList);
  approverConf.value.nodePostList = data.map(item => ({
    id: item.id,
    postCode: item.postCode,
    postName: item.postName
  }));
  approverPostVisible.value = false;
};

const saveApprover = () => {
  if (!checkApprover()) {
    return;
  }
  console.log({
    value: approverConf.value,
    flag: true,
    id: approverConfig.value.id
  });
  formWorkflowStore.updateApproverConfig({
    value: approverConf.value,
    flag: true,
    id: approverConfig.value.id
  });
  closeDrawer();
};

const checkApprover = () => {
  if (approverConf.value.settype === 1) {
    if (
      isEmpty(approverConf.value.nodeUserList) &&
      isEmpty(approverConf.value.nodeRoleList) &&
      isEmpty(approverConf.value.nodePostList)
    ) {
      MessageUtil.warning(i18n.global.t("workflow.flowDesign.pleaseChooseUser"));
      return false;
    }
  } else if (approverConf.value.settype === 2) {
    if (!approverConf.value.approveDirectorLevel) {
      //请选择
      MessageUtil.warning(i18n.global.t("workflow.flowDesign.chooseDeptMange"));
      return false;
    }
  } else if (approverConf.value.settype === 4) {
    if (!approverConf.value.formUserFields) {
      //请选择
      MessageUtil.warning(i18n.global.t("workflow.flowDesign.selectMemberFieldInForm"));
      return false;
    }
  } else if (approverConf.value.settype === 5) {
    if (!approverConf.value.formDeptFields) {
      //请选择
      MessageUtil.warning(i18n.global.t("workflow.flowDesign.selectDeptFieldInForm"));
      return false;
    }
    if (!approverConf.value.formDeptFieldLevel) {
      //请选择
      MessageUtil.warning(i18n.global.t("workflow.flowDesign.chooseDeptMange"));
      return false;
    }
  }
  return true;
};

const closeDrawer = () => {
  formWorkflowStore.updateApprover();
};

// Computed property for user fields
const getUserFieldList = computed(() => formProperties.value.filter(item => item.id.includes("user_select")));
const getDeptFieldList = computed(() => formProperties.value.filter(item => item.id.includes("dept_select")));

const formProperties = computed(() => {
  console.log(formFields);
  return formFields.value
    .filter(item => item.scheme)
    .map((item: any) => ({
      id: item.value,
      name: item.label,
      displayType: item.displayType,
      readable: true,
      writeable: false
    }));
});

const allReadable = ref(false);
const allWriteable = ref(false);

const handleAllReadableChange = (val: boolean) => {
  approverConf.value.formProperties.forEach(item => {
    item.readable = val;
  });
};

const handleAllWriteableChange = (val: boolean) => {
  approverConf.value.formProperties.forEach(item => {
    item.writeable = val;
  });
};

onMounted(() => {
  initApproverConfig(null);
});
</script>

<style lang="scss">
.set_promoter {
  .approver_content {
    padding-bottom: 10px;
    border-bottom: 1px solid #f2f2f2;
    height: 90%;
  }

  .approver_self_select .el-button,
  .approver_content .el-button {
    margin-bottom: 10px;
  }

  .approver_content .el-radio,
  .approver_some .el-radio,
  .approver_self_select .el-radio {
    width: 27%;
  }

  .approver_manager p {
    line-height: 32px;
  }

  .approver_manager select {
    width: 420px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    border: 1px solid rgba(217, 217, 217, 1);
  }

  .approver_manager p.tip {
    margin: 10px 0 22px 0;
    font-size: 12px;
    line-height: 16px;
    color: #f8642d;
  }

  .approver_self {
    padding: 28px 20px;
  }

  .approver_self_select,
  .approver_manager,
  .approver_content,
  .approver_some {
    padding: 20px 20px 0;
  }

  .approver_manager p:first-of-type,
  .approver_some p {
    line-height: 19px;
    font-size: 14px;
    margin-bottom: 14px;
  }

  .approver_self_select h3 {
    margin: 5px 0 20px;
    font-size: 14px;
    font-weight: bold;
    line-height: 19px;
  }

  .selected_list {
    span {
      margin-bottom: 4px;
      margin-right: 4px;
      cursor: pointer;
    }

    a {
      color: var(--el-color-primary);
      line-height: 25px;
      cursor: pointer;
    }
  }
}

.flex-align-center {
  display: flex;
  align-items: center;
}
</style>
